package org.gdstash.character;

import org.gdstash.file.GDReader;
import org.gdstash.file.GDWriter;
import org.gdstash.util.FileVersionException;
import org.gdstash.util.GDMsgFormatter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class GDCharMarkerList {
    private static final int VERSION = 1;
    private static final int BLOCK = 7;
    private int version;
    private ArrayList<List<GDCharUID>> uidLists;

    public GDCharMarkerList() {
        final int size = 3;
        this.uidLists = new ArrayList<List<GDCharUID>>(size);
        for (int i = 0; i < size; ++i) {
            this.uidLists.add(new LinkedList<GDCharUID>());
        }
    }

    public void read() throws IOException {
        int val = 0;
        final GDReader.Block block = new GDReader.Block();
        val = GDReader.readBlockStart(block);
        if (val != 7) {
            throw new FileVersionException(GDMsgFormatter.getString(GDMsgFormatter.rbMsg, "ERR_UNSUPPORTED_VERSION"));
        }
        this.version = GDReader.readEncInt(true);
        if (this.version != 1) {
            throw new FileVersionException(GDMsgFormatter.getString(GDMsgFormatter.rbMsg, "ERR_UNSUPPORTED_VERSION"));
        }
        for (int i = 0; i < this.uidLists.size(); ++i) {
            GDChar.readUIDList(this.uidLists.get(i));
        }
        GDReader.readBlockEnd(block);
    }

    public void write() throws IOException {
        final GDReader.Block block = new GDReader.Block();
        GDWriter.writeBlockStart(block, 7);
        GDWriter.writeInt(1);
        for (int i = 0; i < this.uidLists.size(); ++i) {
            GDChar.writeUIDList(this.uidLists.get(i));
        }
        GDWriter.writeBlockEnd(block);
    }

    public int getByteSize() {
        int size = 0;
        size += 4;
        size += 4;
        size += 4;
        for (int i = 0; i < this.uidLists.size(); ++i) {
            size += 4;
            size += this.uidLists.get(i).size() * GDCharUID.getByteSize();
        }
        size += 4;
        return size;
    }

    public void print() {
        for (int i = 0; i < this.uidLists.size(); ++i) {
            System.out.println("Index : " + Integer.toString(i));
            for (final GDCharUID uid : this.uidLists.get(i)) {
                uid.println();
            }
            System.out.println();
        }
    }
}
